const axios = require('axios');

const host = 'https://mp.weixin.qq.com'

/*//scanloginqrcode
let url= host +"/cgi-bin/scanloginqrcode?action=getqrcode&random=".concat(+new Date);


axios.get(url).then(res=>{
    console.log(res.data)
})

console.log('1' * 1)*/

//必要的初始化参数
let sessionid = +new Date + "" + Math.floor(100 * Math.random())
let currentLang = 'zh_CN'
let isStopQrcodeTimer = !1;

//getQrcode方法
function getQrcode() {
    let url2 = host + '/cgi-bin/bizlogin?action=startlogin';
    axios.post(url2, {
        userlang: currentLang,
        redirect_url: 'pages/login/loginpage',
        login_type: 3,
        sessionid: sessionid
    }, {
        headers: {
            'cookie': "ua_id=ZZryfME61E5O318DAAAAAEPPmfOrYWt1YG24IoDoWzI=;"
        }
    }).then(res => {
        console.log(res.data);
    })
}

function refreshQrcode() {
    // this.getQrcode();
    let qrcodeSrc = 'https://mp.weixin.qq.com' + "/cgi-bin/scanloginqrcode?action=getqrcode&random=".concat(+new Date);
    console.log('访问图片地址:', qrcodeSrc)
}


function ask() {
    const url = host + "/cgi-bin/scanloginqrcode?action=ask";

    return url;
}

/**
 *
 */
async function getHtml() {
    const indexHtmlResp = await axios.get('https://mp.weixin.qq.com/', {
        headers: {
            'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
        }
    });
    let cookieArr = indexHtmlResp.headers['set-cookie'];
    console.log(cookieArr[0].split(';')[0]);
    //主要获取 ua_id
    return cookieArr[0].split(';')[0];

}


/**
 *
 * @param uaIdCookie
 */
async function checkChatPermission(uaIdCookie, wxuin) {

    const url = "https://mp.weixin.qq.com/webpoc/cgi/chat/checkChatPermission?type=15&grayType=random&token=&lang=zh_CN&f=json&ajax=1";

    let cookie = uaIdCookie;
    if (wxuin) {
        cookie += '; ' + wxuin
    }
    const resp = await axios.get(url, {
        headers: {
            'referer': 'https://mp.weixin.qq.com/',
            'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
            'cookie': cookie
        }
    });

    console.log(resp.headers)
    console.log(resp.data)

    //主要获取wxuin
    wxuin = resp.headers['set-cookie'][0].split(';')[0];

    if (!resp.data.can) {
        wxuin = await checkChatPermission(uaIdCookie, wxuin);
    }

    return wxuin;

}

/**
 *
 * @param uaid
 * @param wxuid
 * @return {Promise<void>}
 */
async function bizLogin(uaid, wxuid) {
    let url = "https://mp.weixin.qq.com/cgi-bin/bizlogin"
    const resp = await axios.post(url, {
        action: "prelogin",
        token: '',
        lang: 'zh_CN',
        f: 'json',
        ajax: 1
    }, {
        headers: {
            'content-length': 47,
            'origin': 'https://mp.weixin.qq.com',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'referer': 'https://mp.weixin.qq.com/',
            'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
            'cookie': uaid
        },
        transformRequest: [
            function (data) {
                let ret = ''
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                ret = ret.substring(0, ret.lastIndexOf('&'));
                return ret
            }
        ],
    });

    console.log(resp.data);

}

async function startLogin(uaid) {


    let url = 'https://mp.weixin.qq.com/cgi-bin/bizlogin?action=startlogin';
    const resp = await axios.post(url, {
        userlang: 'zh_CN',
        redirect_url: '',
        login_type: 3,
        sessionid: +new Date + "" + Math.floor(100 * Math.random()),
        token: '',
        lang: 'zh_CN',
        f: 'json',
        ajax: 1
    }, {
        headers: {
            'content-length': 99,
            'origin': 'https://mp.weixin.qq.com',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'referer': 'https://mp.weixin.qq.com/',
            'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
            'cookie': uaid
        },
        transformRequest: [
            function (data) {
                let ret = ''
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                ret = ret.substring(0, ret.lastIndexOf('&'));
                return ret
            }
        ],
    });
    //获取uuid

    console.log(resp.data);
    console.log(resp.headers['set-cookie'][0].split(';')[0]);

    return resp.headers['set-cookie'][0].split(';')[0];
}

const schedule = require('node-schedule');

/**
 * 用来监听二维码扫描
 * @param uaid
 * @param uuid
 * @return {Promise<void>}
 */
async function loginQrCodeAsk(uaid, uuid) {


    console.log(new Date())
    let url = 'https://mp.weixin.qq.com/cgi-bin/scanloginqrcode?action=ask&token=&lang=zh_CN&f=json&ajax=1';
    //
    const resp = await axios.get(url,{
        headers:{
            'content-length': 99,
            'origin': 'https://mp.weixin.qq.com',
            'referer': 'https://mp.weixin.qq.com/',
            'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
            //'cookie':'ua_id=ZKrST10YH5RQRl6RAAAAAB-xKSJ09dPH9wyg38b6ukc=; uuid=5d8171a3a0c251482e46a18b93de5fb9'
        }
    });
    //console.log(resp)

    console.log("开始打印");

    console.log(resp.headers);
    console.log("================")
    console.log(resp.data)
    console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>")

}


async function test() {
    //get uaid
    let uaid = await getHtml();
    //get wxuin
    // let wxuin = await checkChatPermission(uaid);
    //preLogin
    //await bizLogin(uaid);
    //start login
    let uuid = await startLogin(uaid);
    //get qrcodeSrc
    refreshQrcode()
    console.log("cookie:==>", uaid + ';' + uuid);
    //qrcodeSrc need cookie

}


//test();

